package com.ds.esd.localproxy.handler;

import com.ds.common.JDSException;
import com.ds.config.JDSUtil;
import com.ds.esd.client.ESDFacrory;
import com.ds.server.httpproxy.core.*;
import com.ds.vfs.FileInfo;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.vfs.ct.CtVfsService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;


public class VFSResourceHandler extends AbstractRADHandler implements Handler {
    private static final Logger log = Logger.getLogger(VFSResourceHandler.class.getName());
    private String resourceMount;
    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        this.resourceMount = RESOURCE_MOUNT_OPTION.getProperty(server, handlerName);

        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {

        boolean ruleMatches = rule.matcher(request.getUrl()).matches();
        if (!ruleMatches) {
            return false;
        }
        String path = request.getPath();
        String resource = Http.join(resourceMount, path.substring(getUrlPrefix().length()));
        if (log.isLoggable(Level.INFO)) {
            log.info("Loading resource: " + resource);
        }
        String mimeType = getMimeType(resource);
        File file = new File(JDSUtil.getJdsRealPath() + resource);
        InputStream is = null;
        String projectName = this.getProjectName(request);
        String filePath = this.formatPath(request.getUrl(), projectName);

        if (file.exists()) {
            is = new FileInputStream(file);
        } else {
            // 激活下载操作
            FileInfo fileInfo = null;
            try {
                fileInfo = getVfsClient().getFileByPath(path);
            } catch (JDSException e) {
                e.printStackTrace();
            }

            if (fileInfo == null) {
                try {
                    fileInfo = ESDFacrory.getESDClient().getFileByPath(filePath, projectName);
                } catch (JDSException e) {
                    e.printStackTrace();
                }
            }


            if (fileInfo != null) {
                is = fileInfo.getCurrentVersonInputStream();
            }


            if (is != null) {
                response.setMimeType(mimeType);
                response.addHeader("Content-disposition", "filename=" + new String(fileInfo.getName().getBytes("utf-8"), "ISO8859-1"));
            } else {
                log.warning("Resource was not found or the mime type was not understood. (Found file=" + (is != null) + ") (Found mime-type=" + (mimeType != null) + ")");
                return false;
            }

        }


        if (mimeType == null || is == null) {
            log.warning("Resource was not found or the mime type was not understood. (Found file=" + (is != null) + ") (Found mime-type=" + (mimeType != null) + ")");
            return false;
        }
        response.setMimeType(mimeType);
        response.sendResponse(is, Integer.valueOf(Long.toString(file.length())));
        return true;
    }


    public CtVfsService getVfsClient() {
        CtVfsService vfsClient = CtVfsFactory.getCtVfsService();
        return vfsClient;
    }

}
